package com.gl.portal.common;

import com.gl.common.constant.Constants;
import com.gl.common.util.SecurityUtils;
import com.gl.common.util.StringUtils;
import com.gl.framework.security.LoginBody;
import com.gl.framework.security.LoginUser;
import com.gl.framework.security.service.SysLoginService;
import com.gl.portal.system.service.SysMenuService;
import com.gl.portal.system.vo.RouterVo;
import com.gl.portal.system.vo.SysMenuVo;
import com.gl.portal.system.vo.SysUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 登录验证控制器
 */
@RestController
public class SysLoginController {

	@Autowired
	private SysLoginService loginService;

	@Autowired
	private SysMenuService menuService;

	/**
	 * 登录方法
	 *
	 * @param loginBody 登陆信息
	 * @return 结果
	 */
	@PostMapping("/login")
	public Map<String, Object> login(@RequestBody LoginBody loginBody) {
		// 生成令牌
		String token = loginService.login(loginBody.getLoginName(), loginBody.getPassword(), loginBody.getCode(), loginBody.getUuid());

		Map<String, Object> map = new HashMap<String, Object>();
		map.put(Constants.TOKEN, token);

		return map;
	}

	/**
	 * 获取用户信息
	 *
	 * @return 用户信息
	 */
	@GetMapping("userinfo")
	public Map<String, Object> getInfo() {
		LoginUser loginUser = SecurityUtils.getLoginUser();
		SysUserVo user = loginUser.getUser();
		user.setPassword(StringUtils.EMPTY);

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("user", user);
		map.put("roles", loginUser.getRoleKeys());
		map.put("permissions", loginUser.getPermissions());

		return map;
	}

	/**
	 * 获取路由信息
	 *
	 * @return 路由信息
	 */
	@GetMapping("routers")
	public List<RouterVo> getRouters() {
		LoginUser loginUser = SecurityUtils.getLoginUser();
		SysUserVo user = loginUser.getUser();
		Long userId = user.getId();
		List<SysMenuVo> menus = menuService.selectMenuTreeByUserId(userId);
		List<RouterVo> routers = menuService.buildMenus(menus);

		return routers;
	}
}
